package com.enfo.zjabank.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.enfo.zjabank.model.UploadedFile;
import com.enfo.zjabank.service.UploadService;
import com.enfo.zjabank.tool.FileUtil;
import com.enfo.zjabank.tool.StringUtil;
import net.coobird.thumbnailator.Thumbnails;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.lang3.StringEscapeUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.*;

/**
 * Created by zhoum on 2016/7/26.
 */
@Controller
@RequestMapping("/upload")
public class UploadController {
    @Autowired
    private UploadService uploadService;
    @Value("#{propertiesReader[uploadPath]}")
    private String uploadPath;
    @Value("#{propertiesReader[thumbPath]}")
    private String thumbPath;

    private static Logger logger = LoggerFactory.getLogger(UploadedFile.class);

    public void test(HttpServletRequest request, HttpServletResponse response,HttpSession session) {
        System.out.println(session.getId());
        session.setAttribute("inputUser","nmb");
//        Cookie[] cookies = request.getCookies();
//        for (Cookie c : cookies) {
//            System.out.println(c.getName() + "--->" + c.getValue());
//        }
    }

    @RequestMapping(value = "/list/{busiCode}/{busiId}", method = RequestMethod.GET)
    public
    @ResponseBody
    Map listImgs(HttpServletRequest request, HttpServletResponse response, @PathVariable String busiCode, @PathVariable String busiId) {
        if (StringUtil.isEmpty(busiCode) || StringUtil.isEmpty(busiId)) {
            return null;
        }
        List<Map<String, Object>> dataList = new ArrayList<>();
        dataList = uploadService.listImgs(busiCode, busiId);
        if (dataList.size() > 0) {
            Map<String, List> map = new HashMap<String, List>();
            map.put("files", dataList);
            return map;
        }
        return null;
    }

    @RequestMapping(value = "/toUpload/{busiCode}/{inputType}/{queryFlag}", method = RequestMethod.GET)
    public String toUpload(HttpServletRequest request, Model model, @PathVariable String busiCode,@PathVariable String inputType,@PathVariable String queryFlag) {
        String param = request.getParameter("param");
        String old = request.getParameter("old");
        String inputUser = (String) request.getAttribute("inputUser");
        if(inputUser==null){
            inputUser = request.getParameter("inputUser");
        }
        if ("1".equals(old)) {
            return "upload/upload_old";
        }
        if (!StringUtil.isEmpty(param) && !StringUtil.isEmpty(busiCode) && !StringUtil.isEmpty(inputUser) && !StringUtil.isEmpty(inputType)) {
            JSONObject job = (JSONObject) JSON.parse(Base64.decodeBase64(param));
            String debtId = null;
            Map<String, Object> debtInfoMap = new HashMap<>();
            if("change".equals(busiCode)){
                debtId = uploadService.getDebtId((String) job.get("id"));
                debtInfoMap = uploadService.getDebtChangeInfo((String) job.get("id"));
            }else{
                debtId = (String) job.get("id");
                debtInfoMap = uploadService.getDebtInfo(debtId);
            }
            for (Map.Entry<String, Object> entry : debtInfoMap.entrySet()) {
                model.addAttribute(entry.getKey().toString(), entry.getValue());
            }
            model.addAttribute("busiId", debtId);
            model.addAttribute("inputType",inputType);
            boolean uploadRole = true;
            if(!"0".equals(queryFlag)){
                uploadRole = false;
                if("cancelQuery".equals(queryFlag)){
                    busiCode = uploadService.showByState(debtId);
                }
            } else {
                uploadRole = uploadService.uploadRole(inputUser);
            }
            model.addAttribute("queryFlag", queryFlag);
            model.addAttribute("uploadRole", uploadRole);
            model.addAttribute("busiCode", busiCode);
            return "upload/uploadApache";
        }
        return null;
    }

    @RequestMapping(value = {"/get/{type}/{busiCode}/{id}","/get/{type}/{busiCode}/{id}/*"}, method = RequestMethod.GET)
    public void getImg(HttpServletRequest request, HttpServletResponse response,@PathVariable String type, @PathVariable String id, @PathVariable String busiCode) throws IOException {
        if (StringUtil.isEmpty(id) || StringUtil.isEmpty(type) || StringUtil.isEmpty(busiCode)) {
            return;
        }
        String path;
        if ("thumbImg".equals(type)) {
            path = (String) uploadService.getImg(busiCode,id).get("thumb_path");
            response.setContentType("image/png");
        } else {
            path = (String) uploadService.getImg(busiCode,id).get("path");
            response.setContentType("image/png");
        }
        File file = new File(path);
        //判断文件是否存在如果不存在就返回默认图标
        if (file.exists() && file.canRead()) {
//            file = new File(request.getServletContext().getRealPath("/")
//                    + "upload/img/img_not_exists.png");
            FileInputStream inputStream = new FileInputStream(file);
            byte[] data = new byte[(int) file.length()];
            int length = inputStream.read(data);
            inputStream.close();


            OutputStream stream = response.getOutputStream();
            stream.write(data);
            stream.flush();
            stream.close();
        }
    }

    @RequestMapping(value = "/del/{busiCode}/{id}", method = RequestMethod.GET)
    public
    @ResponseBody
    Map<String, List> deleteImg(HttpServletRequest request, HttpServletResponse response,@PathVariable String busiCode, @PathVariable String id) {
//        String id = request.getParameter("id");
//        String inputUser = uploadService.getInputCode(id);
//        if (StringUtil.isEmpty(id) || inputUser == null || !uploadService.uploadRole(String.valueOf(inputUser))) {
//            return null;
//        }
        return uploadService.del(busiCode,id);
    }

    @RequestMapping(value = "/upload", method = RequestMethod.POST)
    public
    @ResponseBody
    Map upload(MultipartHttpServletRequest request, HttpServletResponse response) throws Exception {
        response.setContentType("application/json; charset=UTF-8");
        String inputUser = (String) request.getAttribute("inputUser");
        if(inputUser==null){
            inputUser = request.getParameter("inputUser");
        }
        Map<String, Object> map1;
        List<Map> list = new ArrayList<Map>();
        Map<String, List> map = new HashMap();
        //0. notice, we have used MultipartHttpServletRequest
        String busiId = request.getParameter("busiId");
        String busiCode = request.getParameter("busiCode");
        if (StringUtil.isEmpty(busiCode) || StringUtil.isEmpty(busiId) || StringUtil.isEmpty(inputUser)) {
            return null;
        } else {
            inputUser = uploadService.getInputCode(busiId);
            boolean uploadRole = uploadService.uploadRole(inputUser);
            if (!uploadRole) {
                return null;
            }
        }
        //1. get the file from the request object
        MultipartFile mpf;
        Iterator<String> itr = request.getFileNames();
        while (itr.hasNext()) {
            mpf = request.getFile(itr.next());
            logger.info(StringEscapeUtils.unescapeHtml4(mpf.getOriginalFilename()) + " uploaded!");
            logger.info("file type is :" + mpf.getContentType());
            UploadedFile ufile = new UploadedFile();
            try {
                ufile.setBusiId(busiId);
                ufile.setBusiCode(busiCode);
                ufile.setInputUser(inputUser);
                ufile.setSize(mpf.getBytes().length);
                ufile.setOriginName(StringEscapeUtils.unescapeHtml4(mpf.getOriginalFilename()));
                ufile.setSuffix(ufile.getOriginName().substring(ufile.getOriginName().lastIndexOf(".") + 1));
                ufile.setSaveName(busiId + "_" + new StringBuffer(ufile.getOriginName()).insert(ufile.getOriginName().indexOf("."), System.currentTimeMillis()));
                ufile.setPath(uploadPath + "/" + busiCode + "/" + ufile.getSaveName());
                File file = new File(ufile.getPath());
                file.mkdirs();
                mpf.transferTo(file);
                if (mpf.getContentType().startsWith("image")) {
                    ufile.setFileType("image");
                    ufile.setThumbPath(thumbPath + "/" + busiCode + "/" + ufile.getSaveName() + ".png");
                    new File(thumbPath + "/" + busiCode).mkdirs();
                    Thumbnails.of(file).size(70, 70).toFile(ufile.getThumbPath());
                }
                int id = uploadService.upload(ufile,busiCode);
                //生产返回值
                map1 = new HashMap<String, Object>();
                map1.put("name", ufile.getOriginName());
                map1.put("size", ufile.getSize());
                map1.put("url", "/server/upload/get/file/" +busiCode+"/" + id + "/" + map1.get("name"));
                if (mpf.getContentType().startsWith("image")) {
                    map1.put("thumbnailUrl", "/server/upload/get/thumbImg/"+busiCode+"/" + id);
                }
                map1.put("deleteUrl", "/server/upload/del/"+busiCode+"/" + id);
                map1.put("deleteType", "GET");
                list.add(map1);
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            String path = request.getParameter("path");
            if(!StringUtil.isEmpty(path)){
                FileUtil.deleteFiles(path);
            }
        }
        if (list.size() > 0) {
            map.put("files", list);
            logger.debug("返回json:" + map);
            return map;
        }
        return null;
    }

    @RequestMapping(value = "/change",method = RequestMethod.POST)
    public @ResponseBody String change(String id){
        if(!StringUtil.isEmpty(id)){
            uploadService.attachementsChange(id);
            return "success";
        }else{
            return "fail";
        }
    }

    @RequestMapping(value = "/test1",method = RequestMethod.GET)
    public void test1(){
        System.out.println("test1");
    }
    @RequestMapping(value = "/test1/test2",method = RequestMethod.GET)
    public void test2(){
        System.out.println("test2");
    }
}
